package com.learning.rocketmq.springbootclient.spring;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

/**
 * ClassName: ProducerService
 * Description:
 * 1、application.yml 文件里加入自己命名的参数，然后通过＠Value 注解引人。如NameServer 的地址、GoupName 名称和Topic 名称等
 * 2、把发送消息和消费消息的功能封装成 Service
 * 3、Producer和Consumer 的初始化比较慢，不建议每发一个消息或者消费一个消息就启动和注销对应的Object，
 * 所以适合把初始化操作代码写到@PostConstruct 函数里，把关闭操作代码写到@PreDestroy 函数里
 *
 *
 * Date: 2019/1/15 11:43 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@Service
public class ProducerService {

    private DefaultMQProducer producer = null;

    @PostConstruct
    public void initMQProducer() {
        producer = new DefaultMQProducer("producerGroupName");
        producer.setNamesrvAddr("");
        producer.setRetryTimesWhenSendFailed(3);
        try {
            producer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

    public void send(String topic, String msg) {
        Message message = new Message(topic, "", "", msg.getBytes());
        try {
            producer.send(message);
            return;
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }
    }

    @PreDestroy
    public void shutDownProducer() {
        if (producer != null) {
            producer.shutdown();
        }
    }

}
